package com.lkeqi.usercenter.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkeqi.usercenter.common.BaseResponse;
import com.lkeqi.usercenter.constant.Constant;
import com.lkeqi.usercenter.dto.request.RegisterRequestParam;
import com.lkeqi.usercenter.entity.User;
import com.lkeqi.usercenter.enums.ErrorCode;
import com.lkeqi.usercenter.exception.BusinessException;
import com.lkeqi.usercenter.mapper.UserMapper;
import com.lkeqi.usercenter.service.UserService;
import com.lkeqi.usercenter.utils.ResultUtils;
import com.lkeqi.usercenter.utils.Sm4Util;
import com.lkeqi.usercenter.utils.UserCenterUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author Lenovo
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-04-12 10:00:20
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public BaseResponse<Long> userRegister(RegisterRequestParam registerRequestParam) {
        if (StringUtils.isAllBlank(registerRequestParam.getUserNo(), registerRequestParam.getPwd(), registerRequestParam.getCheckPwd(), registerRequestParam.getPlanetCode())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "请求参数不能为空！");
        }
        if (registerRequestParam.getPlanetCode().length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "星球编号超长！");
        }
        if (!registerRequestParam.getPwd().equals(registerRequestParam.getCheckPwd())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "密码与确认密码不一致！");
        }
        if (UserCenterUtils.containsSpecialCharacters(registerRequestParam.getUserNo())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "用户编号包含非法字符！");
        }
        long count = this.count(new LambdaQueryWrapper<User>().eq(User::getUserNo, registerRequestParam.getUserNo()));
        if (count > 0) {
            throw new BusinessException(ErrorCode.REGISTER_ERROR , "用户编号已存在！");
        }
        long planetCount = this.count(new LambdaQueryWrapper<User>().eq(User::getPlanetCode, registerRequestParam.getPlanetCode()));
        if (planetCount > 0) {
            throw new BusinessException(ErrorCode.REGISTER_ERROR , "星球编号已存在！");
        }
        String encryptPwd;
        try {
            encryptPwd = Sm4Util.encrypt(registerRequestParam.getPwd());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        User user = new User();
        user.setUserNo(registerRequestParam.getUserNo());
        user.setPwd(encryptPwd);
        user.setPlanetCode(registerRequestParam.getPlanetCode());
//        user.setUsername(userDto.getUsername());
//        user.setTel(userDto.getTel());
//        user.setEmail(userDto.getEmail());
//        user.setGender(userDto.getGender());
        Assert.isTrue(this.save(user), "用户添加失败!");
        return ResultUtils.success(user.getId(),"注册成功!");
    }

    @Override
    public BaseResponse<User> login(String userNo, String password, HttpServletRequest request) {
        if (StringUtils.isAllBlank(userNo, password)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户编号和密码不能为空!");
        }
        if (UserCenterUtils.containsSpecialCharacters(userNo)) {
            throw new BusinessException(ErrorCode.LOGIN_ERROR, "用户编号包含非法字符!");
        }
        String encryptPwd;
        try {
            encryptPwd = Sm4Util.encrypt(password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserNo, userNo).eq(User::getPwd, encryptPwd));
        if (user == null) {
            log.info("login error userNo:{}, password:{} check you input", userNo, password);
            throw new BusinessException(ErrorCode.LOGIN_ERROR, "用户名或密码错误!");
        }
        //记录用户登陆状态
        //如何知道是哪个用户登录了？
        //1.连接服务器端，得到一个session状态，返回给前端
        //2.登录成功后，得到了登录成功的session，返回给前端一个设置‘cookie’的命令
        // session =》 cookie
        //3.前端接收到后端的命令后，设置cookie，保存到浏览器中
        //4.前端再次请求后端的时候(相同的域名) ，在请求头中带上cookie去请求
        //5.后端拿前端的cookie，找到对应的session
        //6.后端从session中可以取出基于该session存储的变量(用户登录名、信息)
        //用户脱敏
        User safeUser = getSafeUser(user);
        request.getSession().setAttribute(Constant.USER_STATE_LOGIN, safeUser);
        return ResultUtils.success(safeUser,"登陆成功！");
    }

    @Override
    public BaseResponse<List<User>> list(String username, HttpServletRequest request) {
        if (isNotAdmin(request)) {
            log.info("no auth to search user");
            throw new BusinessException(ErrorCode.NO_AUTH);

        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            userLambdaQueryWrapper.like(User::getUsername, username);
        }
        List<User> list = this.list(userLambdaQueryWrapper);
        List<User> userList = list.stream().map(this::getSafeUser).toList();
        return ResultUtils.success(userList);
    }

    @Override
    public BaseResponse deleteById(long id, HttpServletRequest request) {
        if (id <= 0) {
            log.info("id is null");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"id is null");
        }
        if (isNotAdmin(request)) {
            log.info("no auth to delete user");
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return ResultUtils.success(this.removeById(id));
    }


    private boolean isNotAdmin(HttpServletRequest request) {
        Object userObject = request.getSession().getAttribute(Constant.USER_STATE_LOGIN);
        User user = (User) userObject;
        return ObjectUtils.isEmpty(user) || user.getUserRole() != Constant.ADMIN_ROLE;
    }

    @Override
    public User getSafeUser(User user) {
        if (user == null) {
            return null;
        }
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUserNo(user.getUserNo());
        safeUser.setUsername(user.getUsername());
        safeUser.setUserRole(user.getUserRole());
        safeUser.setTel(user.getTel());
        safeUser.setEmail(user.getEmail());
        safeUser.setGender(user.getGender());
        safeUser.setProfileUrl(user.getProfileUrl());
        safeUser.setPlanetCode(user.getPlanetCode());
        return safeUser;
    }

    @Override
    public BaseResponse<Integer> logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.USER_STATE_LOGIN);
        return ResultUtils.success(1,"注销成功！");
    }
}




